﻿// This code was taken from Git and modified.
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Text;
using System;
using Newtonsoft.Json.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using SimpleRest.Core.Extensions.Exceptions;
using SimpleRest.Core.Extensions.Documentation;
using SimpleRest.Serialization;

namespace SimpleRest.Core.Extensions.Media
{
    [GeneralDescription("Form url encoding media type support.  Only Content-Type is supported for this formatter.  Specifying this media type formatter in the Accept header will result in a 415 status code.")]
    public class FormUrlEncodingMediaTypeFormatter : IMediaTypeFormatter
    {
        private readonly UrlEncodedFormPostSerializer _serializer = new UrlEncodedFormPostSerializer();

        public IEnumerable<string> SupportedMediaTypes
        {
            get
            {
                return new List<string>()
                {
                    "application/x-www-form-urlencoded"
                };
            }
        }

        public System.IO.Stream Serialize(object obj)
        {
            throw new MediaTypeNotSupportedException(false);
        }

        public object DeSerialize(System.IO.Stream stream, Type type)
        {
            System.IO.Stream str; String strmContents;
            Int32 counter, strLen, strRead;
            // Create a Stream object.
            str = stream;
            // Find number of bytes in stream.
            strLen = Convert.ToInt32(str.Length);
            // Create a byte array.
            byte[] strArr = new byte[strLen];
            // Read stream into byte array.
            strRead = str.Read(strArr, 0, strLen);

            Dictionary<string, string> items = new Dictionary<string,string>();
            string text = System.Text.Encoding.UTF8.GetString(strArr);
            foreach (var kvp in HttpUtility.UrlDecode(text).Split(new char[] { '&' }))
            {
                var split = kvp.Split(new char[] { '=' });
                string key = split[0];
                string value = "";
                if (split.Length > 1)
                    value = split[1];

                items.Add(key, value);
            }

            return _serializer.DeSerialize(type, items);
            //return FormUrlEncodingUtility.DeSerialize(System.Text.Encoding.UTF8.GetString(strArr), type);
           // throw new NotImplementedException();
        }

        public bool CanSerialize(Type type)
        {
            if (type == null) return true;
            return false;
        }

        public bool CanDeserialize(Type type)
        {
            if (type == null) return true;
            return _serializer.CanDeserialize(type);
        }
    }
}